package org.thingsboard.server.controller;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.DecodedJWT;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.CustomerConfig;
import org.thingsboard.server.common.data.Tenant;
import org.thingsboard.server.common.data.User;
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.page.PageLink;
import org.thingsboard.server.common.data.security.Authority;
import org.thingsboard.server.common.data.security.UserCredentials;
import org.thingsboard.server.common.data.security.model.JwtSettings;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.install.InstallScripts;
import org.thingsboard.server.service.security.auth.jwt.RefreshTokenRepository;
import org.thingsboard.server.service.security.auth.jwt.settings.JwtSettingsService;
import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.security.model.UserPrincipal;
import org.thingsboard.server.service.security.model.token.AccessJwtToken;

import org.thingsboard.server.common.data.security.model.JwtToken;
import org.thingsboard.server.service.security.model.token.JwtTokenFactory;
import org.thingsboard.server.utils.AdvancedEncryption;
import org.thingsboard.server.utils.MapCacheUtil;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.util.*;
import java.util.stream.Collectors;


@RestController
@TbCoreComponent
@Slf4j
public class AuthLoginController extends BaseController {

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Autowired
    private JwtTokenFactory tokenFactory;

    @Autowired
    private RefreshTokenRepository refreshTokenRepository;

    @Autowired
    private InstallScripts installScripts;
//
//    @Value("${security.oauth2.clients.default.clientId}")
//    private String clientId;
//    @Value("${security.oauth2.clients.default.clientSecret}")
//    private String clientSecret;
//    @Value("${security.oauth2.clients.default.accessTokenUri}")
//    private String accessTokenUri;
//    @Value("${security.oauth2.clients.default.scope}")
//    private String scope;
    @Value("${security.oauth2.clients.default.redirectUriTemplate}")
    private String redirectUriTemplate;
//    @Value("${security.oauth2.clients.default.authorizationGrantType}")
//    private String authorizationGrantType;
    @Value("${security.oauth2.clients.default.homeUri}")
    private String homeUri;
    @Value("${security.oauth2.clients.default.mapperConfig.basic.defaultEmail}")
    private String defaultEmail;
    @Value("${security.oauth2.clients.default.mapperConfig.basic.algorithm}")
    private String algorithm;
    @Value("${security.oauth2.clients.default.mapperConfig.basic.algorithmKey}")
    private String key;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Resource
    private MapCacheUtil mapcacheutil;

//    @RequestMapping("/login/oauth2/code")
//    public void getToken(@RequestParam(value = "code", required = false) String code,
//                         HttpServletRequest request,
//                         HttpServletResponse response) {
//        OAuth2AccessToken oAuth2AccessToken = null;
//        try {
//            oAuth2AccessToken = exchangeToken(code);
//            Claims decode;
//            decode = parseJWT(oAuth2AccessToken.getTokenValue());
//         //   decode = JWT.decode("eyJraWQiOiIzUG1OMllUOUpEZ09tWmhJcUh2TzM1OXlYQ3NDWU9aem0zRXMwSzVDZzdFIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiI3MTYyNTk0OTQxNzQxMzAxNzYwIiwiYXVkIjoiZDZlOTNlMzYwOTJjNDk1MGI2NTg5NzMwZGE5MDk5YjMiLCJncmFudF90eXBlIjoiYXV0aG9yaXphdGlvbl9jb2RlIiwidXNlcl9pZCI6NzE2MjU5NDk0MTc0MTMwMTc2MCwiaXNfcmVmcmVzaF90b2tlbiI6MCwiaXNzIjoiaHR0cDovL3BsYXRmb3JtLnBhYXMyLmNoaW5hcG9zdC5jb20uY24iLCJuYW1lIjoi546L5bCR6IejIiwiZXhwIjoxNjg5MzI1Mzc1LCJpc19zZXJ2aWNlX3VzZXIiOjAsImp0aSI6ImY3Y2QwNWZmLTdiZmYtNDkxYi1hNjUxLTUyMjYxODBiMjUxYyIsInNpZCI6IjUyYWU1NGIxLTE2ZjgtNDI1NS1hYTVkLTY4MmQ0YjRkNGVlNCIsInVzZXJuYW1lIjoid2FuZ3NoYW9jaGVuIn0.jy5Ew1eN4iSXFNU5-Gwc8wl2ONWVho-eUUjpVFsWpY41IoYYANC-UCa7z6dGFu_Ffm_cIk0c7OoLhub51U1woQyGH8vrp-MBLqPo0uMQKQJMnqAIQD_B1O7ewLspFmmVtkrp-VNW_phrfAXpBkwX6VFuY_hPo2pIZnnXKXai-iI");
//            String username = getUsernameFromToken(decode);
//            TenantId devOpsId = getTenantIdFromUsername(username);
//            processToken(username, devOpsId, response, request);
//        } catch (Exception e) {
//            handleException(e, oAuth2AccessToken, response);
//        }
//    }



    @PostMapping("/sendValue")
    public Map<String, Object> sendValue(@RequestBody String data, HttpServletRequest request,
                                         HttpServletResponse response) throws ThingsboardException, IOException {
        Map map = JSONObject.parseObject(data, Map.class);
        //获取用户名和处理中心编号
        String username = (String) map.get("username");
        String oldName = "";
        try {
            oldName = AdvancedEncryption.decryptString(String.valueOf(map.get("oldName")), algorithm, key);
        } catch (Exception e) {
            throw new ThingsboardException("解密原用户名错误", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
        }
        TenantId devOpsId = new TenantId(UUID.nameUUIDFromBytes(username.getBytes()));
        //先查询有无对应租户
        User user = userService.findUserByEmail(devOpsId, username.concat(defaultEmail));
        Map<String, Object> jsonResponse = new HashMap<>();
        if (user != null) {
            if (mapcacheutil.get(oldName.concat(username)).equals(Authority.TENANT_ADMIN.name())) {
                log.info("租户已存在 - " + user.toString());
                jsonResponse.put("redirectUrl", oauthTokenLogin(user, request, response));
            } else {
                jsonResponse.put("redirectUrl", oauthTokenLogin(getOrCreateCustomer(user, oldName), request, response));
            }
        } else {
            log.info("无对应处理中心租户信息:" + username);
            jsonResponse.put("redirectUrl", homeUri + "/login/selectUser");
        }
        return jsonResponse;
    }

    @Autowired
    JwtTokenFactory jwtTokenFactory;

    @Autowired
    JwtSettingsService jwtSettingsService;




    @GetMapping("/getcustomerConfig")
    public ResponseEntity<CustomerConfig> getcustomerConfig(String orguser) throws ThingsboardException, IOException {
        // 处理请求逻辑
        CustomerConfig  customerConfig = customerConfigService.findCustomerConfigByOrgUser(orguser);
        return new ResponseEntity<>(customerConfig, HttpStatus.OK);
    }

    private TenantId getTenantId(String tenantName, TenantId devOpsId) throws IOException {
        List<Tenant> tenants = tenantService.findTenants(new PageLink(1, 0, tenantName)).getData();
        Tenant tenant;
        if (tenants == null || tenants.isEmpty()) {
            tenant = new Tenant();
            tenant.setTitle(defaultEmail.replace("@", ""));
            tenant.setId(devOpsId);
            tenant = tenantService.saveDevOpsTenant(tenant);
            installScripts.createDefaultRuleChains(tenant.getId());
            log.info("创建租户 - " + tenant.toString());
        } else {
            tenant = tenants.get(0);
        }
        return tenant.getTenantId();
    }

    private String concatenateCustomerConfigInfo(List<CustomerConfig> customerConfigs) {
        return customerConfigs.stream()
                .map(config -> config.getOrgUser() + ":" + config.getOrgName())
                .collect(Collectors.joining(","));
    }

    private String oauthTokenLogin(User saveUser, HttpServletRequest request, HttpServletResponse response) {
        //登录
        JwtToken accessToken;
        JwtToken refreshToken;
        try {
            UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, saveUser.getEmail());
            SecurityUser securityUser = new SecurityUser(saveUser, true, principal);
            AccessJwtToken accessToken1 = (AccessJwtToken) tokenFactory.createAccessJwtToken(securityUser);
            accessToken= new JwtToken() {
                @Override
                public String getToken() {
                    return accessToken1.getToken();
                }
            } ;
            refreshToken = refreshTokenRepository.requestRefreshToken(securityUser);
        } catch (Exception e) {
            log.error("Can't get or create security user from oauth2 user", e);
            throw new RuntimeException("Can't get or create security user from oauth2 user", e);
        }
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(homeUri);
        builder.path("/");
        builder.queryParam("accessToken", accessToken);
        builder.queryParam("refreshToken", refreshToken);
        URI location = builder.build().toUri();
        log.info("重定向 - " + location.toString());
        return homeUri + "/home/?accessToken=" + accessToken.getToken()
                + "&refreshToken=" + refreshToken.getToken();
    }

    private CustomerId getCustomerId(TenantId tenantId, String customerName) {
        if (StringUtils.isEmpty(customerName)) {
            return null;
        }
        Optional<Customer> customerOpt = customerService.findCustomerByTenantIdAndTitle(tenantId, customerName);
        if (customerOpt.isPresent()) {
            return customerOpt.get().getId();
        } else {
            Customer customer = new Customer();
            customer.setTenantId(tenantId);
            customer.setTitle(customerName);
            return customerService.saveCustomer(customer).getId();
        }
    }

    private User getOrCreateCustomer(User user, String oldName) {
        //判断处理中心租户是否存在，存在则以devops用户作为登录用户，登录租户下的用户
        User customerUser = new User();
        if (user != null) {
            boolean equals = user.getCustomerId().getId().toString().equals(TenantId.SYS_TENANT_ID.getId().toString());
            CustomerId customerId = user.getCustomerId() != null && !equals ?
                    user.getCustomerId() : getCustomerId(user.getTenantId(), oldName.concat(defaultEmail));
            String customer = user.getEmail();//oldName.concat("_").concat(user.getEmail());
            customerUser.setEmail(customer);
            customerUser.setCustomerId(customerId);
            customerUser.setAuthority(Authority.CUSTOMER_USER);
            TenantId tenantId = user.getTenantId();
            customerUser.setTenantId(tenantId);
            User loginCustomer = userService.findUserByEmail(tenantId, customer);
            if (loginCustomer == null) {
                customerUser = userService.saveUser(customerUser.getTenantId(),customerUser);
                log.info("创建用户 - " + customerUser.toString());
                UserCredentials userCredentials = userService.findUserCredentialsByUserId(customerUser.getTenantId(), customerUser.getId());
                if (userCredentials == null) {
                    userService.activateUserCredentials(customerUser.getTenantId(), userCredentials.getActivateToken(), passwordEncoder.encode(""));
                }
            } else {
                customerUser = loginCustomer;
            }
        }
        return customerUser;
    }
//
//    private OAuth2AccessToken exchangeToken(String code) {
//        log.info("重写自定义认证 - " + code);
//        RestTemplate restTemplate = new RestTemplate();
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//        LinkedMultiValueMap<String, String> multiValueMap = new LinkedMultiValueMap<>();
//        multiValueMap.add("code", code);
//        multiValueMap.add("grant_type", authorizationGrantType);
//        multiValueMap.add("redirect_uri", redirectUriTemplate);
//        multiValueMap.add("scope", scope);
//        multiValueMap.add("client_id", clientId);
//        multiValueMap.add("client_secret", clientSecret);
//        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(multiValueMap, headers);
//        log.info("开始向oauth2认证 - " + multiValueMap.toString());
//        ResponseEntity<OAuth2AccessToken> responseEntity = null;
//        OAuth2AccessToken oAuth2AccessToken;
//        try {
//            responseEntity = restTemplate.exchange(
//                    accessTokenUri,
//                    HttpMethod.POST,
//                    httpEntity,
//                    OAuth2AccessToken.class
//            );
//            log.info("auth2认证成功" + multiValueMap.toString());
//            oAuth2AccessToken = responseEntity.getBody();
//            log.info("获取token信息 - " + oAuth2AccessToken.toString());
//            return oAuth2AccessToken;
//        } catch (RestClientException e) {
//            throw new RuntimeException("auth2认证失败", e);
//        }
//    }

    private Claims parseJWT(String token) {
        try {
            // 解析token、获得laims、jwt中荷载中申明的对象
            Claims claims = (Claims)Jwts.parser()
                    .setSigningKey("1234")
                    .parse(token)
                    .getBody();

            return  claims;
        } catch (Exception e) {
            throw new RuntimeException("解析token失败" + token, e);
        }
    }


    private String getUsernameFromToken(DecodedJWT decode) {
        String username = decode.getClaim("username").asString();
        username = "sdyz_futianshun";
        log.info("用户名 - " + username);
        return username;
    }

    private TenantId getTenantIdFromUsername(String username) {
        return new TenantId(UUID.nameUUIDFromBytes(username.getBytes()));
    }

    private void processToken(String username, TenantId devOpsId, HttpServletResponse response, HttpServletRequest request) throws Exception {
        List<CustomerConfig> customerConfigList = customerConfigService.findCustomerConfigByUsername(username);

        if (customerConfigList.size() == 1) {
            // 处理单个用户情况
            processSingleUser(customerConfigList.get(0), username, devOpsId, response, request);
        } else if (customerConfigList.size() > 1) {
            // 处理多个用户情况
            processMultipleUsers(customerConfigList, username, response);
        } else {
            log.info("无对应处理中心租户信息:" + username);
            response.sendRedirect(homeUri + "/login/selectUser");
        }
    }

    private void processSingleUser(CustomerConfig customerConfig, String username, TenantId devOpsId, HttpServletResponse response, HttpServletRequest request) throws IOException {
        String orgUserName = customerConfig.getOrgUser();
        String authority = customerConfig.getAuthority();
        log.info("Org User: " + orgUserName);

        User user = userService.findUserByEmail(devOpsId, orgUserName.concat("defaultEmail"));
        if (user == null) {
            log.info("无对应处理中心租户信息:" + username);
            response.sendRedirect(homeUri + "/login/selectUser");
        } else {
            if (authority.equals(Authority.TENANT_ADMIN.name())) {
                log.info("租户已存在 - " + user.toString());
                response.sendRedirect(oauthTokenLogin(user, request, response));
            } else {
                response.sendRedirect(oauthTokenLogin(getOrCreateCustomer(user, username), request, response));
            }
        }
    }

    private void processMultipleUsers(List<CustomerConfig> customerConfigList, String username, HttpServletResponse response) throws Exception {
        customerConfigList.forEach(x -> {
            mapcacheutil.add(x.getLoginUser().concat(x.getOrgUser()), x.getAuthority(), 60000);
        });
        response.sendRedirect(homeUri + "/login/selectUser?usertoken=" + AdvancedEncryption.encryptString(username, algorithm, key));
    }

    private void handleException(Exception e, OAuth2AccessToken oAuth2AccessToken, HttpServletResponse response) {
        throw new RuntimeException("根据邮箱查询租户出错或新建租户出错", e);
    }



    @PostMapping("/customerConfigData")
    @ResponseBody
    public ResponseEntity<String> customerConfigData(@RequestBody String data, HttpServletRequest request,
                                                     HttpServletResponse response) throws ThingsboardException, IOException {
//    public ResponseEntity<String> doPost(@RequestBody @NonNull String data) throws ThingsboardException {
        Map map = JSONObject.parseObject(data, Map.class);
        //获取用户名和处理中心编号
        String userName;
        //userName = "sdyz_futianshun";
        try {
            userName = AdvancedEncryption.decryptString((String) map.get("username"), algorithm, key);
        } catch (Exception e) {
            throw new ThingsboardException("解密用户名错误", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
        }
        // 处理请求逻辑
        List<CustomerConfig> customerConfigList = customerConfigService.findCustomerConfigByUsername(userName);
        String concatenatedInfo = concatenateCustomerConfigInfo(customerConfigList);
        JSONObject jsonResponse = new JSONObject();
        jsonResponse.put("orgUserAndOrgName", concatenatedInfo);
        jsonResponse.put("config",customerConfigList);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        log.info(String.valueOf(jsonResponse));
        return new ResponseEntity<>(jsonResponse.toString(), headers, HttpStatus.OK);
    }


}
